<template>
  <el-config-provider :locale="zhCn">
    <div class="department-manage">
      <!-- 筛选条件区域 -->
      <filter-form v-model="filterForm" :form-items="formItems" @search="handleSearch" @reset="resetFilter" @update:modelValue="handleFilterChange" />

      <!-- 操作按钮区域 -->
      <div class="operation-section">
        <el-button type="primary" @click="handleAdd">新增部门</el-button>
      </div>

      <!-- 列表展示区域 -->
      <div class="table-section">
        <el-table
          :data="treeTableData"
          row-key="deptId"
          border
          default-expand-all
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          style="width: 100%"
          v-loading="loading"
          class="custom-table"
        >
          <el-table-column prop="deptName" label="部门名称" min-width="120" show-overflow-tooltip />
          <el-table-column prop="orderNum" label="排序" width="80" align="center" />
          <el-table-column prop="leader" label="负责人" min-width="100" show-overflow-tooltip />
          <el-table-column prop="phone" label="联系电话" min-width="120" show-overflow-tooltip />
          <el-table-column prop="email" label="邮箱" min-width="150" show-overflow-tooltip />
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="row.status === '0' ? 'success' : 'info'">{{ row.status === '0' ? '正常' : '停用' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" min-width="180" show-overflow-tooltip />
          <el-table-column label="操作" width="180" fixed="right" align="center">
            <template #default="{ row }">
              <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
              <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total" @pagination="handlePagination" />

      <!-- 新增/编辑部门对话框 -->
      <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '新增部门' : '编辑部门'" width="500px" destroy-on-close class="department-dialog">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" class="department-form">
          <el-form-item v-if="!(dialogType === 'edit' && form.parentId === 0)" label="上级部门" prop="parentId">
            <el-tree-select
              v-model="form.parentId"
              :data="treeTableData"
              :props="{
                label: 'deptName',
                value: 'deptId',
                children: 'children'
              }"
              placeholder="请选择上级部门"
              class="w-full"
              check-strictly
              :render-after-expand="false"
              :default-expanded-keys="expandedKeys"
              @change="handleParentChange"
            />
          </el-form-item>
          <el-form-item label="部门名称" prop="deptName">
            <el-input v-model="form.deptName" placeholder="请输入部门名称" />
          </el-form-item>
          <el-form-item label="显示顺序" prop="orderNum">
            <el-input-number v-model="form.orderNum" :min="0" :max="999" />
          </el-form-item>
          <el-form-item label="负责人" prop="leader">
            <el-input v-model="form.leader" placeholder="请输入负责人" />
          </el-form-item>
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入联系电话" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email" placeholder="请输入邮箱" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </el-config-provider>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { getDepartmentList, addDepartment, editDepartment, deleteDepartment } from '@/api/companyMange/departmentMange';
import type { Department, AddDeptParams, EditDeptParams } from '@/api/companyMange/departmentMange';
import zhCn from 'element-plus/es/locale/lang/zh-cn';
import FilterForm from '@/components/FilterForm/index.vue';
import Pagination from '@/components/Pagination/index.vue';
import type { FormItem } from '@/components/FilterForm/index.vue';

interface ApiResponse<T = any> {
  code: number;
  msg: string;
  data: T;
}

// 筛选表单
const filterForm = reactive({
  deptName: '',
  status: ''
});

// 表单项配置
const formItems = computed<FormItem[]>(() => [
  {
    label: '部门名称',
    prop: 'deptName',
    type: 'input',
    placeholder: '请输入部门名称'
  },
  {
    label: '状态',
    prop: 'status',
    type: 'select',
    placeholder: '请选择状态',
    options: [
      { label: '正常', value: '0' },
      { label: '停用', value: '1' }
    ]
  }
]);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 加载状态
const loading = ref(false);

// 表格数据
const tableData = ref<Department[]>([]);

// 树形表格数据
const treeTableData = ref<Department[]>([]);

// 默认展开的节点
const expandedKeys = ref<(string | number)[]>([]);

// 对话框相关
const dialogVisible = ref(false);
const dialogType = ref<'add' | 'edit'>('add');
const formRef = ref();
const form = reactive<AddDeptParams & { deptId?: number | string }>({
  deptId: '',
  parentId: 0,
  deptName: '',
  orderNum: '0',
  leader: '',
  phone: '',
  email: ''
});

// 表单校验规则
const rules = {
  deptName: [{ required: true, message: '请输入部门名称', trigger: 'blur' }],
  orderNum: [{ required: true, message: '请输入显示顺序', trigger: 'blur' }],
  leader: [{ required: true, message: '请输入负责人', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
};

// 将扁平数据转换为树形结构
const convertToTree = (data: Department[]) => {
  const result: Department[] = [];
  const map: { [key: string | number]: Department } = {};

  // 先将数据转换为map
  data.forEach((item) => {
    map[item.deptId] = { ...item, children: [] };
  });

  // 构建树形结构
  data.forEach((item) => {
    const node = map[item.deptId];
    if (item.parentId === 0) {
      result.push(node);
    } else {
      if (map[item.parentId]) {
        map[item.parentId].children?.push(node);
      }
    }
  });

  return result;
};

// 获取部门列表
const getList = async () => {
  loading.value = true;
  try {
    const res = (await getDepartmentList({
      deptName: filterForm.deptName,
      status: filterForm.status
    })) as unknown as ApiResponse<Department[]>;

    if (res.code === 200) {
      tableData.value = res.data;
      treeTableData.value = convertToTree(res.data);
      total.value = res.data.length;
    } else {
      ElMessage.error(res.msg || '获取部门列表失败');
    }
  } catch (error) {
    ElMessage.error('获取部门列表失败');
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  getList();
};

// 重置筛选
const resetFilter = () => {
  filterForm.deptName = '';
  filterForm.status = '';
  currentPage.value = 1;
  pageSize.value = 10;
  handleSearch();
};

// 分页方法
const handlePagination = ({ pageNum, pageSize: size }: { pageNum: number; pageSize: number }) => {
  currentPage.value = pageNum;
  pageSize.value = size;
  getList();
};

// 处理筛选条件变化
const handleFilterChange = (val: any) => {
  filterForm.deptName = val.deptName || '';
  filterForm.status = val.status || '';
};

// 新增部门
const handleAdd = () => {
  dialogType.value = 'add';
  // 新增时不设置默认上级部门
  Object.assign(form, {
    deptId: '',
    parentId: '',
    deptName: '',
    orderNum: '0',
    leader: '',
    phone: '',
    email: ''
  });
  expandedKeys.value = [];
  dialogVisible.value = true;
};

// 编辑部门
const handleEdit = (row: Department) => {
  dialogType.value = 'edit';
  Object.assign(form, {
    deptId: row.deptId,
    parentId: row.parentId,
    deptName: row.deptName,
    orderNum: row.orderNum.toString(),
    leader: row.leader,
    phone: row.phone,
    email: row.email
  });
  // 设置默认展开的节点
  expandedKeys.value = [row.parentId];
  dialogVisible.value = true;
};

// 删除部门
const handleDelete = async (row: Department) => {
  try {
    await ElMessageBox.confirm('确定要删除该部门吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    await deleteDepartment(row.deptId);
    ElMessage.success('删除成功');
    getList();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
    }
  }
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          await addDepartment(form as AddDeptParams);
          ElMessage.success('新增成功');
        } else {
          await editDepartment(form as EditDeptParams);
          ElMessage.success('编辑成功');
        }
        dialogVisible.value = false;
        getList();
      } catch (error) {
        ElMessage.error(dialogType.value === 'add' ? '新增失败' : '编辑失败');
      }
    }
  });
};

// 处理选择变化
const handleParentChange = (val: number | string) => {
  expandedKeys.value = [val];
};

// 初始化
onMounted(() => {
  getList();
});
</script>

<style lang="scss" scoped>
.department-manage {
  padding: 20px;
  min-height: calc(100vh - 40px);

  .operation-section {
    margin-bottom: 20px;
    display: flex;
    gap: 12px;
  }

  .table-section {
    background-color: #fff;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

    .custom-table {
      :deep(.el-table__header) {
        th {
          background-color: #f5f7fa;
          color: #606266;
          font-weight: 600;
        }
      }

      :deep(.el-table__row) {
        &:hover {
          td {
            background-color: #f5f7fa;
          }
        }
      }
    }
  }
}

.department-dialog {
  :deep(.el-dialog__body) {
    padding: 20px 30px;
  }

  .department-form {
    .el-form-item {
      margin-bottom: 22px;
    }
  }
}

:deep(.el-button) {
  display: inline-flex;
  align-items: center;
  gap: 4px;
}
</style>
